﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using SYcwpb.Models;
using SYcwpb.Commands;
using System.Windows.Input;
using SYcwpb.Helpers;
using SYcwpb.Views;
using SYcwpb.WinForm;
using SYcwpb.Access;
using System.Media;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace SYcwpb.ViewModels
{
    class StatisticsViewModel:ViewModelBase,IDataErrorInfo
    {
        private bool IsAutoStaSaved = true;
        private bool IsSaveStaAsk = true;

        private StatisticsView _view;

        public  StatisticsAccess StatisticsAccess = new StatisticsAccess();
        /// <summary>
        /// 参数字典
        /// </summary>
        private Dictionary<string, string> DicParaMeters = new Dictionary<string, string>();


        #region 公里数自动统计



        public double driverMileage = 0;
        public double followMileage = 0;

        private UnStatisticsDatesModel _selectedDate;
        public UnStatisticsDatesModel SelectedDate
        {
            get { return _selectedDate; }
            set
            {
                if (value == _selectedDate)
                    return;
                _selectedDate = value;

                OnPropertyChanged("SelectedDate");
            }
        }

        private ObservableCollection<UnStatisticsDatesModel> _unStatisticsDatesCollections;
        public ObservableCollection<UnStatisticsDatesModel> UnStatisticsDatesCollections
        {
            get
            {
                if (null == _unStatisticsDatesCollections)
                    InitUnStatisticsDatesCollections();

                return _unStatisticsDatesCollections;
            }

        }

        private DataTable _autoStaResultDT;
        public DataTable AutoStaResultDT
        {
            get {return _autoStaResultDT;}
            set
            {
                _autoStaResultDT = value;
                OnPropertyChanged("AutoStaResultDT");
            }
        }
        private ICommand _calc_KilometreCommand;
        public ICommand Calc_KilometreCommand
        {
            get
            {
                if (_calc_KilometreCommand == null)
                    _calc_KilometreCommand = new RelayCommands(para => this.Calc_KilometreCommand_Methos());
                return _calc_KilometreCommand;
            }
        }
        private ICommand _auto_CalulateCommand;
        public ICommand Auto_CalulateCommand
        {
            get
            {
                if (null == _auto_CalulateCommand)
                    _auto_CalulateCommand = new RelayCommands(para => this.Auto_CalulateCommand_Method());

                return _auto_CalulateCommand;
            }
            
        }

        public ICommand _auto_SaveCommand;
        public ICommand Auto_SaveCommand
        {
            get
            {
                if (null == _auto_SaveCommand)
                    _auto_SaveCommand = new RelayCommands(para => this.Auto_SaveCommand_Method());

                return _auto_SaveCommand;
            }
        }
#endregion

        #region 公里数、工时手动输入
        private DataTable _manualStaResultDT;
        public DataTable ManualStaResultDT
        {
            get { return _manualStaResultDT; }
            set
            {
                _manualStaResultDT = value;
                OnPropertyChanged("ManualStaResultDT");
            }
        }

        private string _manual_SelectDate;
        public string Manual_SelectDate
        {
            get { return _manual_SelectDate; }
            set
            {
                DateTime curT = Convert.ToDateTime(value);
                if (_manual_SelectDate == curT.ToString("yyyy-MM-dd"))
                    return;
                _manual_SelectDate = curT.ToString("yyyy-MM-dd");
            }
        }

        public ObservableCollection<SingleDriverModel> _driverCollections;
        public ObservableCollection<SingleDriverModel> DriverCollections
        {
            get { return _driverCollections; }
            set
            {
                _driverCollections = value;
            }
        }

        private SingleDriverModel _singleDriver; 
        public SingleDriverModel SingleDriver
        {
            get { return _singleDriver; }
            set
            {
                if (value == _singleDriver)
                    return;

                _singleDriver = value;

                OnPropertyChanged("SingleDriver");
            }
        }


        public ObservableCollection<ClassModel> _classCollections;
        public ObservableCollection<ClassModel> ClassCollections
        {
            get
            {
                if (null == _classCollections)
                    _classCollections = new ObservableCollection<ClassModel>()
                    {
                        new ClassModel(){ID = "0",ClassName = "早班"},
                        new ClassModel(){ID = "2",ClassName = "白班"},
                        new ClassModel(){ID = "3",ClassName = "夜班"}
                    };

                return _classCollections;
            }
        }

        private ClassModel _mana_Selectd_Class;
        public ClassModel Mana_Selectd_Class 
        {
            get { return _mana_Selectd_Class; }
            set {
                if (value == _mana_Selectd_Class)
                    return;

                _mana_Selectd_Class = value;
                OnPropertyChanged("Mana_Selectd_Class");
            }
        }

        private string _mana_Miles = "0";
        public string Mana_Miles
        {
            get { return _mana_Miles; }
            set
            {
                if (value == _mana_Miles)
                    return;

                _mana_Miles = value;
                OnPropertyChanged("Mana_Miles");
            }
        }

        private string _mana_Hours = "0";
        public string Mana_Hours
        {
            get { return _mana_Hours; }
            set
            {
                if (value == _mana_Hours)
                    return;

                _mana_Hours = value;
                OnPropertyChanged("Mana_Hours");
            }
        }

        private int _mana_SelectIndex = -1;
        public int Mana_SelectIndex
        {
            get { return _mana_SelectIndex; }
            set
            {
                if (value == _mana_SelectIndex)
                    return;
                _mana_SelectIndex = value;
                OnPropertyChanged("Mana_SelectIndex");
            }
        }
        private ICommand _manaual_SetZeroCommand;
        public ICommand Manaual_SetZeroCommand
        {
            get
            {
                if (_manaual_SetZeroCommand == null)
                    _manaual_SetZeroCommand = new RelayCommands(para => this.Manaual_SetZeroCommand_Method());
                return _manaual_SetZeroCommand;
            }
        }
        private ICommand _manaual_ModifyCommand;
        public ICommand Manaual_ModifyCommand
        {
            get{
                if(_manaual_ModifyCommand==null)
                    _manaual_ModifyCommand=new RelayCommands(para => this.Manaual_ModifyCommand_Method(),
                        para => this.Can_Manaual_AddCommand_Method());
                return _manaual_ModifyCommand;
            }
        }
        private ICommand _manaual_AddCommand;
        public ICommand Manaual_AddCommand
        {
            get
            {
                if (null == _manaual_AddCommand)
                    _manaual_AddCommand = new RelayCommands(para => this.Manaual_AddCommand_Method(),
                        para => this.Can_Manaual_AddCommand_Method());
                return _manaual_AddCommand;
            }
        }
#endregion

        #region 公里数、工时月查看

        private DateTime _view_StartDate = DateTime.Now;
        public DateTime View_StartDate
        {
            get { return _view_StartDate; }
            set
            {
                //DateTime curT = Convert.ToDateTime(value);
                if (_view_StartDate == value)
                    return;
                _view_StartDate = value;
                OnPropertyChanged("View_StartDate");
            }
        }

        private DateTime _view_Both_EndDate = DateTime.Now;
        public DateTime View_Both_EndDate
        {
            get { return _view_Both_EndDate; }
            set
            {
                ;
            }
        }

        private DateTime _view_EndDate = DateTime.Now;
        public DateTime View_EndDate
        {
            get { return _view_EndDate; }
            set
            {
                //DateTime curT = Convert.ToDateTime(value);
                if (_view_EndDate == value)
                    return;
                _view_EndDate = value;

                OnPropertyChanged("View_EndDate");
            }
        }
        private SingleDriverModel _view_SingleDriver;
        public SingleDriverModel View_SingleDriver
        {
            get { return _view_SingleDriver; }
            set
            {
                if (value == _view_SingleDriver)
                    return;

                _view_SingleDriver = value;
                OnPropertyChanged("View_SingleDriver");
            }
        }

        public DataTable _view_SafeMilesDT;
        public DataTable View_SafeMilesDT
        {
            get { return _view_SafeMilesDT; }
            set
            {
                _view_SafeMilesDT = value;
                OnPropertyChanged("View_SafeMilesDT");
            }
        }

        public DataTable _view_FollowMilesDT;
        public DataTable View_FollowMilesDT
        {
            get { return _view_FollowMilesDT; }
            set
            {
                _view_FollowMilesDT = value;
                OnPropertyChanged("View_FollowMilesDT");
            }
        }

        private DataTable _view_HoursDT;
        public DataTable View_HoursDT
        {
            get { return _view_HoursDT; }
            set
            {
                _view_HoursDT = value;
                OnPropertyChanged("View_HoursDT");
            }
        }

        private ICommand _view_QuertCommand;
        public ICommand View_QueryCommand
        {
            get
            {
                if (null == _view_QuertCommand)
                    _view_QuertCommand = new RelayCommands(para => this.View_QueryCommand_Method());

                return _view_QuertCommand;
            }
        }

        #endregion

        #region 参数设置
        //private string _inMiles;
        //public string InMiles
        //{ 
        //    get{return _inMiles;}
        //    set { 
        //        if (_inMiles == value)
        //            return;
        //        _inMiles = value;
        //        OnPropertyChanged("InMiles");
        //    }
        //}

        //private string _outMiles;
        //public string OutMiles
        //{
        //    get { return _outMiles; }
        //    set
        //    {
        //        if (_outMiles == value)
        //            return;
        //        _outMiles = value;
        //        OnPropertyChanged("OutMiles");
        //    }
        //}

        //private string _upToChangedMiles;
        //public string UpToChangedMiles
        //{
        //    get { return _upToChangedMiles; }
        //    set
        //    {
        //        if (_upToChangedMiles == value)
        //            return;
        //        _upToChangedMiles = value;
        //        OnPropertyChanged("UpToChangedMiles");
        //    }
        //}

        //private string _hkhupToChangedMiles;
        //public string HKHUpToChangedMiles
        //{
        //    get { return _hkhupToChangedMiles; }
        //    set
        //    {
        //        if (_hkhupToChangedMiles == value)
        //            return;
        //        _hkhupToChangedMiles = value;
        //        OnPropertyChanged("HKHUpToChangedMiles");
        //    }
        //}

        //private string _downToChangedMiles;
        //public string DownToChangedMiles
        //{
        //    get { return _downToChangedMiles; }
        //    set
        //    {
        //        if (_downToChangedMiles == value)
        //            return;
        //        _downToChangedMiles = value;
        //        OnPropertyChanged("DownToChangedMiles");
        //    }
        //}

        //private string _totalMiles;
        //public string TotalMiles
        //{
        //    get { return _totalMiles; }
        //    set
        //    {
        //        if (_totalMiles == value)
        //            return;
        //        _totalMiles = value;
        //        OnPropertyChanged("TotalMiles");
        //    }
        //}

        //private string _hkhtotalMiles;
        //public string HKHTotalMiles
        //{
        //    get { return _hkhtotalMiles; }
        //    set
        //    {
        //        if (_hkhtotalMiles == value)
        //            return;
        //        _hkhtotalMiles = value;
        //        OnPropertyChanged("HKHTotalMiles");
        //    }
        //}

        private string _milePrice;

        private string _hourPrice;

        //private bool _readOnly = true;
        //public bool ReadOnly
        //{
        //    get { return _readOnly; }
        //    set
        //    {
        //        if (value == _readOnly)
        //            return;

        //        _readOnly = value;
        //        OnPropertyChanged("ReadOnly");
        //    }
        //}

        //private ICommand _para_EditCommand;
        //public ICommand Para_EditCommand
        //{
        //    get
        //    {
        //        if (null == _para_EditCommand)
        //            _para_EditCommand = new RelayCommands(para=>this.Para_EditCommand_Method(),
        //                para => this.Can_Para_EditCommand_Method());

        //        return _para_EditCommand;
        //    }
        //}

        //private ICommand _para_Save;
        //public ICommand Para_Save
        //{
        //    get
        //    {
        //        if (null == _para_Save)
        //            _para_Save = new RelayCommands(para=>this.Para_Save_Method(),
        //                para=>this.Can_Para_Save_Method());

        //        return _para_Save;
        //    }
        //}

        //private ICommand _para_Cancel;
        //public ICommand Para_Cancel
        //{
        //    get
        //    {
        //        if (null == _para_Cancel)
        //            _para_Cancel = new RelayCommands(para => this.Para_Cancel_Method(),
        //                para => this.Can_Para_Cancel_Method());

        //        return _para_Cancel;
        //    }
        //}
#endregion

        public string Error
        {
            get { return null; }
        }

        public string this[string columnName]
        {
            get
            {
                string error = null;
                switch (columnName)
                {
                    case "Mana_Miles":
                        error = Validate(_mana_Miles);
                        break;
                    case "Mana_Hours":
                        error = Validate(_mana_Hours);
                        break;
                }
                return error;
            }
        }

        public StatisticsViewModel(StatisticsView view)
        {
            InitParameters();

            InitManaualDriverCollections();

            _view = view;
        }
        private void Calc_KilometreCommand_Methos()
        {

            try
            {
                _view.btnCalcKiloMetre.Text = CalcKilometre(AutoStaResultDT).ToString("0.00");
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }
        }
        private double GetDouble(object obj)
        {
            double result = 0;
            if (obj != null)
            {
                result = Convert.ToDouble(obj);
            }
            return result;

        }
        private int GetInt(object obj)
        {
            int result = 0;
            if (obj != null)
            {
                result=Convert.ToInt32(obj);
            }
            return result;
                
        }

        private double CalcKilometre(DataTable dt)
        {
            double calcResult = 0;
            if (AutoStaResultDT != null && AutoStaResultDT.Rows.Count > 0)
            {
                for (int i = 0; i < AutoStaResultDT.Rows.Count; i++)
                {

                    calcResult += GetDouble(AutoStaResultDT.Rows[i]["SafeMiles"]);
                }

            }
            return calcResult;
        }
        private void Auto_CalulateCommand_Method()
        {
            if (null == _selectedDate)
            {
                MessageBoxHelper.ShowError("请先选择需要自动统计的日期！");
                return;
            }
            
            DataTable resultDt = StatisticsAccess.GetSelectedDateResult(_selectedDate.AssignDate);
            if (null == resultDt || resultDt.Rows.Count < 1)
            {
                MessageBoxHelper.ShowError(string.Format("暂无 {0} 的出勤数据，请等待轮班操作后重试！", _selectedDate.AssignDate));
                return;
            }

            if (IsAutoStaSaved == false)
            {
                if (!MessageBoxHelper.ShowYesNoAndWarning(string.Format("当前统计尚未保存，是否继续？")))
                    return;
            }

            followMileage=driverMileage = 0;



            InitAutoStaResultDT();
            DataTable tmpData = AutoStaResultDT.Clone();

            UpdateAutoStaResultDT(resultDt);

            CorrectMiles();

            IsAutoStaSaved = false;

            for (int i = 0; i < resultDt.Rows.Count; i++)
            {

                driverMileage += Convert.ToDouble(AutoStaResultDT.Rows[i]["SafeMiles"].ToString());
                followMileage += Convert.ToDouble(AutoStaResultDT.Rows[i]["FollowMiles"].ToString());

            }
        }

        private void InitAutoStaResultDT()
        {
            if (null != AutoStaResultDT)
            {
                AutoStaResultDT.Rows.Clear();
                return;
            }

            AutoStaResultDT = new DataTable();

            AutoStaResultDT.Columns.Add("ID",typeof(int));    //自增标识号
            AutoStaResultDT.Columns.Add("UserID", typeof(string)); //司机工号
            AutoStaResultDT.Columns.Add("Name", typeof(string));
            AutoStaResultDT.Columns.Add("Group", typeof(string));
            AutoStaResultDT.Columns.Add("LineID", typeof(string));
            AutoStaResultDT.Columns.Add("PostName", typeof(string));
            AutoStaResultDT.Columns.Add("CrossRoadID", typeof(string));
            AutoStaResultDT.Columns.Add("CrossingRoad", typeof(string));
            AutoStaResultDT.Columns.Add("GrpType", typeof(string));
            AutoStaResultDT.Columns.Add("SafeMiles", typeof(double));
            AutoStaResultDT.Columns.Add("FollowMiles", typeof(double));
            AutoStaResultDT.Columns.Add("WorkHours", typeof(double));
            AutoStaResultDT.Columns.Add("IsCorrected", typeof(bool));  //标识该行是否已经执行公里数更新的

            AutoStaResultDT.Columns["SafeMiles"].AllowDBNull = false;
            AutoStaResultDT.Columns["FollowMiles"].AllowDBNull = false;
            AutoStaResultDT.Columns["WorkHours"].AllowDBNull = false;
        }

        /// <summary>
        /// 更新自动统计出来的数据
        /// </summary>
        private void UpdateAutoStaResultDT(DataTable resultDT)
        {

            for (int i = 0; i < resultDT.Rows.Count; i++)
            {
                DataRow row = AutoStaResultDT.NewRow();

                bool isBC = false;
                
                string reptrain = resultDT.Rows[i]["reptrain"].ToString();
                if (reptrain.Contains("便"))
                    isBC = true;

                string attenPlace = resultDT.Rows[i]["attenPlace"].ToString();
                string offPlace = resultDT.Rows[i]["offPlace"].ToString();
                string stringruntrain = resultDT.Rows[i]["CrossingRoad"].ToString();

                row["ID"] = resultDT.Rows[i]["ID"];
                row["UserID"] = resultDT.Rows[i]["UserID"].ToString();
                row["Name"] = resultDT.Rows[i]["Name"].ToString();
                row["PostName"] = resultDT.Rows[i]["PostName"].ToString();
                row["Group"] = GetClassNameByID(resultDT.Rows[i]["Group"].ToString());
                row["LineID"] = resultDT.Rows[i]["LineID"].ToString();

                row["GrpType"] = GetSpecialGroup(resultDT.Rows[i]["GrpType"].ToString());

                row["CrossRoadID"] = resultDT.Rows[i]["CrossRoadID"].ToString(); // 用来匹配相同组司机的
                row["CrossingRoad"] = stringruntrain;

                //row["SafeMiles"] = GetMiles(stringruntrain, attenPlace, offPlace, isBC);
                if (string.IsNullOrEmpty(resultDT.Rows[i]["Miles"].ToString()))
                    row["SafeMiles"] = 0;
                else 
                    row["SafeMiles"] = Convert.ToDouble(resultDT.Rows[i]["Miles"].ToString());
                row["FollowMiles"] = row["SafeMiles"];

                if (string.IsNullOrEmpty(resultDT.Rows[i]["WorkHours"].ToString()))
                    row["WorkHours"] = 0;
                else
                    row["WorkHours"] = Convert.ToDouble(resultDT.Rows[i]["WorkHours"]);

                row["IsCorrected"] = false;

                AutoStaResultDT.Rows.Add(row);
            }

        }

        /// <summary>
        /// 根据职务更正自动统计结果中安全驾驶里程和跟车里程字段
        /// </summary>
        private void CorrectMiles()
        {
            if (null == AutoStaResultDT || AutoStaResultDT.Rows.Count < 1)
                return;
            //int crCount=(from item int AutoStaResultDT where item)
            //double zongCount = 0;
            for (int i = 0; i < AutoStaResultDT.Rows.Count; i ++ )
            {
                if (string.IsNullOrEmpty(AutoStaResultDT.Rows[i]["CrossRoadID"].ToString()))   //如果是没有交路号的司机不用检查
                    continue;

                if (Convert.ToBoolean(AutoStaResultDT.Rows[i]["IsCorrected"]) == true)  //如果这个司机已经检查更新过了就继续循环
                    continue;

                string firID = AutoStaResultDT.Rows[i]["ID"].ToString();
                string firPostName = AutoStaResultDT.Rows[i]["PostName"].ToString();
                string firCrossRoadID = AutoStaResultDT.Rows[i]["CrossRoadID"].ToString();
                double miles = Convert.ToDouble(AutoStaResultDT.Rows[i]["SafeMiles"]);
                //CrossingRoad
                List<DataRow> sameCrossingRoadDrivers = new List<DataRow>();
                sameCrossingRoadDrivers.Add(AutoStaResultDT.Rows[i]);
                for (int k = 0; k < AutoStaResultDT.Rows.Count; k++) //找出与第一个司机跑同一交路的司机
                {
                    if (AutoStaResultDT.Rows[k]["ID"].ToString() != firID && AutoStaResultDT.Rows[k]["CrossRoadID"].ToString() == firCrossRoadID)
                    {
                        sameCrossingRoadDrivers.Add(AutoStaResultDT.Rows[k]);
                    }
                }
                double count = (from item in sameCrossingRoadDrivers where item["PostName"].ToString() == "电客车司机" select item).Count();
                bool flag = false;
                foreach (var item in sameCrossingRoadDrivers)
                {
                    if(item["PostName"].ToString()=="电客车司机")
                    {
                        item["SafeMiles"] = Math.Round(miles / count, 1, MidpointRounding.AwayFromZero);
                        item["FollowMiles"] = 0;
                        //zongCount += miles / count;
                        flag=true;
                    }
                    else
                    {
                        item["FollowMiles"] = miles;
                        item["SafeMiles"] = 0;
                    }
                    item["IsCorrected"] = true;
                }
                
                if (!flag&&miles>0){
                    DataTable dt = new CrossingRoadAccess().GetCrossingRoadById(firCrossRoadID);
                    if(dt!=null&&dt.Rows.Count>0)
                        MessageBoxHelper.ShowTips("开行交路 "+dt.Rows[0]["crname"]+"的司机组没有电客车司机");
                }

            }
            //MessageBoxHelper.ShowTips(zongCount + "");
        }

        private void Auto_SaveCommand_Method()
        {
            if (null == _selectedDate)
            {
                MessageBoxHelper.ShowError("请先选择需要自动统计的日期！");
                return;
            }

            if (null == AutoStaResultDT || AutoStaResultDT.Rows.Count < 1)
            {
                MessageBoxHelper.ShowError("没有需要保存的数据");
                return;
            }

            if (DataRowValidation.ExcutedCheckedDataGridValidation(_view.auto_dgv))
            {
                return;
            } 

            if (StatisticsAccess.CheckIsMilesAdded(_selectedDate.AssignDate))
            {
                MessageBoxHelper.ShowError(string.Format("{0} 日的公里数已经自动统计过了",_selectedDate.AssignDate));
                return;
            }
            string calcResult = CalcKilometre(AutoStaResultDT).ToString("0.00");
            double driverMile = 0,followMile=0;
            for (int i = 0; i < AutoStaResultDT.Rows.Count; i++)
            {
                driverMile += Convert.ToDouble(AutoStaResultDT.Rows[i]["SafeMiles"]);
                followMile += Convert.ToDouble(AutoStaResultDT.Rows[i]["FollowMiles"]);
            }
            if (driverMile != driverMileage||followMile != followMileage)
            {
                if (!MessageBoxHelper.ConfirmYesNo("安全驾驶里程与初始不符，现公里合计为:" + calcResult + "，是否保存？"))
                    return;
            }
            //AutoStaResultDT


            if (StatisticsAccess.SaveAutoStaResust(_autoStaResultDT, _selectedDate.AssignDate))
            {
                IsAutoStaSaved = true;


                MessageBoxHelper.ShowTips(string.Format("{0} 日公里数保存成功，公里数合计为：{1}", _selectedDate.AssignDate, calcResult));

                UnStatisticsDatesCollections.Remove(SelectedDate);

                AutoStaResultDT.Rows.Clear();
            }
            else
                MessageBoxHelper.ShowError(string.Format("{0} 日公里数保存时出现异常，请确认数据格式无误后重试！", _selectedDate.AssignDate));
        }

        public void Manaual_SelectDateResult()
        {
            InitManaualStaResultDT();

            DataTable resultDT = StatisticsAccess.Manaual_SelectDateResult(_manual_SelectDate);
            if (null == resultDT || resultDT.Rows.Count < 1)
            {
                MessageBoxHelper.ShowTips("暂无此日统计数据！");
                return;
            }

            UpdateManaualStaResultDT(resultDT);
        }

        private void InitManaualStaResultDT()
        {
            if (null != ManualStaResultDT)
            {
                ManualStaResultDT.Rows.Clear();
                return;
            }

            ManualStaResultDT = new DataTable();

            ManualStaResultDT.Columns.Add("ID", typeof(string));
            ManualStaResultDT.Columns.Add("UserID", typeof(string));
            ManualStaResultDT.Columns.Add("Name", typeof(string));
            ManualStaResultDT.Columns.Add("PostName", typeof(string));
            ManualStaResultDT.Columns.Add("Group", typeof(string));
            ManualStaResultDT.Columns.Add("LineID", typeof(string));
            ManualStaResultDT.Columns.Add("Date", typeof(string));
            ManualStaResultDT.Columns.Add("SafeMiles", typeof(double));
            ManualStaResultDT.Columns.Add("FollowMiles", typeof(double));
            ManualStaResultDT.Columns.Add("WorkHours", typeof(double));

            ManualStaResultDT.RowChanged += new DataRowChangeEventHandler(ManualStaResultDT_RowChanged);
        }

        private void InitManaualDriverCollections()
        {
           DataTable DriverDT =  StatisticsAccess.GetDriversCollections();
           if (null == DriverDT || DriverDT.Rows.Count < 1)
               return;

            if (null == DriverCollections)
            {
                DriverCollections = new ObservableCollection<SingleDriverModel>();
            }
           for (int i = 0; i < DriverDT.Rows.Count; i++)
           {
               SingleDriverModel model = new SingleDriverModel();
               model.ID = DriverDT.Rows[i]["user_id"].ToString();
               model.UserID = DriverDT.Rows[i]["user_name"].ToString();
               model.Name = DriverDT.Rows[i]["user_view_name"].ToString();
               model.Line = DriverDT.Rows[i]["user_line"].ToString();
               model.PostName = DriverDT.Rows[i]["post_name"].ToString();

               DriverCollections.Add(model);
            }
        }
        
        private bool Can_Manaual_AddCommand_Method()
        {
            bool r1 = string.IsNullOrEmpty(Validate(_mana_Miles));
            bool r2 = string.IsNullOrEmpty(Validate(_mana_Hours));
            bool r3 = (Mana_Selectd_Class != null) && !string.IsNullOrEmpty(Mana_Selectd_Class.ID.ToString());
            bool r4 = SingleDriver != null;

            return r1 && r2 && r3 && r4;
        }
        private void Manaual_ModifyCommand_Method()
        {
            IsSaveStaAsk = false;
            try
            {
                if (null == _manual_SelectDate)
                {
                    MessageBoxHelper.ShowError("请先选择日期");
                    return;
                }

                if (!StatisticsAccess.CheckIsMilesAdded(_manual_SelectDate))
                {
                    MessageBoxHelper.ShowError(string.Format("{0}尚未未进行自动统计，不能进行手工输入。请先进行自动统计！", _manual_SelectDate));
                    return;
                }

                int index = -1;
                if (Manaual_CheckhasDriverRecod(ref index))
                {
                    DataRow row = ManualStaResultDT.Rows[index];
                    if (row["PostName"].ToString() == "电客车司机")
                    {
                        row["SafeMiles"] = _mana_Miles;
                    }
                    else
                    {
                        row["FollowMiles"] = _mana_Miles;
                    }
                    row["WorkHours"] = _mana_Hours;
                    if(StatisticsAccess.SaveManaualEditChange(row))
                        MessageBoxHelper.ShowTips("保存成功");
                    else
                        MessageBoxHelper.ShowTips("保存失败");
                }
                else
                {
                    MessageBoxHelper.ShowTips("没有在表中找到司机，请先添加");
                }
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }
            IsSaveStaAsk = true;
        }
        private void Manaual_SetZeroCommand_Method()
        {
            try
            {
                if (null == _manual_SelectDate)
                {
                    MessageBoxHelper.ShowError("请先选择日期");
                    return;
                }
                IsSaveStaAsk = false;
                if (ManualStaResultDT != null)
                {
                    for (int i = 0; i < ManualStaResultDT.Rows.Count; i++)
                    {
                        ManualStaResultDT.Rows[i]["SafeMiles"] = 0;
                        ManualStaResultDT.Rows[i]["FollowMiles"] = 0;
                        ManualStaResultDT.Rows[i]["WorkHours"] = 0;
                    }
                }
                if (MessageBoxHelper.ConfirmYesNo("保存修改？"))
                {
                    for (int i = 0; i < ManualStaResultDT.Rows.Count; i++)
                    {
                        ManualStaResultDT.Rows[i]["SafeMiles"] = 0;
                        ManualStaResultDT.Rows[i]["FollowMiles"] = 0;
                        ManualStaResultDT.Rows[i]["WorkHours"] = 0;
                        StatisticsAccess.SaveManaualEditChange(ManualStaResultDT.Rows[i]);
                    }
                }
                else
                {
                    //e.Row.RejectChanges();
                    Manaual_SelectDateResult();
                }
            }
            catch (Exception ex)
            {
                
                MessageBoxHelper.ShowError(ex);
            }
            IsSaveStaAsk = true;
        }

        private void Manaual_AddCommand_Method()
        {
            if (null == _manual_SelectDate)
            {
                MessageBoxHelper.ShowError("请先选择日期");
                return;
            }

            if (!StatisticsAccess.CheckIsMilesAdded(_manual_SelectDate))
            {
                MessageBoxHelper.ShowError(string.Format("{0}尚未未进行自动统计，不能进行手工输入。请先进行自动统计！", _manual_SelectDate));
                return;
            }

            ///如果已经存在的，就跳到那一行，提示进行修改
            int index = -1;
            if (Manaual_CheckhasDriverRecod(ref index))
            {
                MessageBoxHelper.ShowTips(string.Format("{0}统计结果中，已经存在工号 ：{1}，{2} 司机的公里数信息，请在表格中进行相应修改！", _manual_SelectDate, SingleDriver.UserID, SingleDriver.Name));
                Mana_SelectIndex = index;
                return;
            }

            //增加新的一行
            int newID = -1;
            if (StatisticsAccess.ManaualAddNew(_singleDriver,_manual_SelectDate,_mana_Selectd_Class.ID,_mana_Miles,_mana_Hours,ref newID))
            {
                //前端增加一行
                ManualStaResultDT_AddNewRow(newID);

                MessageBoxHelper.ShowTips(string.Format("插入司机 {0} 公里数数据成功，详情请查看表单最后一行！", SingleDriver.Name));

                SingleDriver = null;
                Mana_Miles = "0";
                Mana_Hours = "0";
                Mana_Selectd_Class = null;
            }
            else
            {
                MessageBoxHelper.ShowError("插入新行失败，请重试！");
            }
        }

        /// <summary>
        /// 在result表中插入新的一行
        /// </summary>
        /// <param name="rowID">为数据库插入新行后返回的主键ID</param>
        private void ManualStaResultDT_AddNewRow(int rowID)
        {
            DataRow row = ManualStaResultDT.NewRow();

            row["ID"] = rowID.ToString();
            row["UserID"] = _singleDriver.UserID;
            row["Name"] = _singleDriver.Name;
            row["Group"] = _mana_Selectd_Class.ClassName;
            row["LineID"] = _singleDriver.Line;
            row["Date"] = _manual_SelectDate;
            row["PostName"] = _singleDriver.PostName;
            if (_singleDriver.PostName == "电客车司机")
            {
                row["SafeMiles"] = _mana_Miles;
                row["FollowMiles"] = "0";
            }
            else
            {
                row["SafeMiles"] = "0";
                row["FollowMiles"] = _mana_Miles;
            }
            row["WorkHours"] = _mana_Hours;

            ManualStaResultDT.Rows.Add(row);

            Mana_SelectIndex = ManualStaResultDT.Rows.Count - 1;
        }

        private void ManualStaResultDT_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Change&&IsSaveStaAsk)
                if (MessageBoxHelper.ConfirmYesNo("保存修改？"))
                {
                    if (StatisticsAccess.SaveManaualEditChange(e.Row))
                    {
                        MessageBoxHelper.ShowTips("保存修改成功！");
                        return;
                    }
                }
                else
                {
                    //e.Row.RejectChanges();
                    Manaual_SelectDateResult();
                }
        }

        public bool Manaual_DeleteRow(DataRow row)
        {
            return StatisticsAccess.DeleteManaualRow(row);
        }

        private void UpdateManaualStaResultDT(DataTable resultDT)
        {
            for (int i = 0; i < resultDT.Rows.Count; i++)
            {
                DataRow row = ManualStaResultDT.NewRow();
                row["ID"] = resultDT.Rows[i]["ID"].ToString();
                row["UserID"] = resultDT.Rows[i]["UserID"].ToString();
                row["Name"] = resultDT.Rows[i]["Name"].ToString();
                row["PostName"] = resultDT.Rows[i]["PostName"].ToString();
                row["Group"] = GetClassNameByID(resultDT.Rows[i]["Group"].ToString());
                row["LineID"] = resultDT.Rows[i]["LineID"].ToString();
                row["Date"] = resultDT.Rows[i]["Date"].ToString();
                row["SafeMiles"] = Convert.ToDouble(resultDT.Rows[i]["SafeMiles"]);
                row["FollowMiles"] = Convert.ToDouble(resultDT.Rows[i]["FollowMiles"]);
                row["WorkHours"] = Convert.ToDouble(resultDT.Rows[i]["WorkHours"]);

                ManualStaResultDT.Rows.Add(row);
            }
        }

        /// <summary>
        /// 检查当天的结果里是否已经有该司机的记录
        /// </summary>
        /// <returns></returns>
        public bool Manaual_CheckhasDriverRecod(ref int index)
        {
            for (int i = 0;SingleDriver!=null&& i < ManualStaResultDT.Rows.Count; i++)
            {
                if (ManualStaResultDT.Rows[i]["UserID"].ToString() == SingleDriver.UserID)
                {
                    index = i;
                    return true;
                }
            }
            return false;
        }

        private void View_QueryCommand_Method()
        {
            int days = (_view_EndDate - _view_StartDate).Days;
            if (days < 0)
            {
                MessageBoxHelper.ShowError("请选择开始日期小于截止日期!");
                return;
            }
            if (days > 180)
            {
                MessageBoxHelper.ShowError("请选择日期跨度小于六个月");
            }

            double mileprice = Convert.ToDouble(_milePrice);
            double hourPrice = Convert.ToDouble(_hourPrice);

            //电客车司机Table
            View_SafeMilesDT = StatisticsAccess.GetViewMilesDT(_view_StartDate, days,1);
            DataTable safeMilesRecordDT = StatisticsAccess.getSafeMilesRecordInDays(_view_StartDate.ToString("yyyy-MM-dd"),_view_EndDate.ToString("yyyy-MM-dd"));
            if (null != safeMilesRecordDT && safeMilesRecordDT.Rows.Count > 0)
            {
                View_SafeMilesDT.PrimaryKey = new DataColumn[] { View_SafeMilesDT.Columns["ID"]};
                foreach(DataRow row in safeMilesRecordDT.Rows)
                {
                    DataRow viewRow = View_SafeMilesDT.Rows.Find(row["UserID"].ToString());
                    if (null != viewRow)
                    {
                        viewRow[row["date"].ToString().Substring(5)] = Convert.ToDouble(viewRow[row["date"].ToString().Substring(5)]) + Convert.ToDouble(row["miles"]);

                        viewRow["总里程"] = Convert.ToDouble(viewRow["总里程"]) + Convert.ToDouble(row["miles"]);

                        viewRow["计价"] = Convert.ToDouble(viewRow["计价"]) + Convert.ToDouble(row["miles"]) * mileprice; 
                    }
                }
            }
            //非电科车司机Table
            View_FollowMilesDT = StatisticsAccess.GetViewMilesDT(_view_StartDate, days, 0);
            DataTable followMilesRecordDT = StatisticsAccess.getfollowMilesRecordInDays(_view_StartDate.ToString("yyyy-MM-dd"), _view_EndDate.ToString("yyyy-MM-dd"));
            if (null != followMilesRecordDT && followMilesRecordDT.Rows.Count > 0)
            {
                View_FollowMilesDT.PrimaryKey = new DataColumn[] { View_FollowMilesDT.Columns["ID"] };
                foreach (DataRow row in followMilesRecordDT.Rows)
                {
                    DataRow viewRow = View_FollowMilesDT.Rows.Find(row["UserID"].ToString());
                    if (null != viewRow)
                    {
                        viewRow[row["date"].ToString().Substring(5)] = Convert.ToDouble(viewRow[row["date"].ToString().Substring(5)]) + Convert.ToDouble(row["miles"]);

                        viewRow["总里程"] = Convert.ToDouble(viewRow["总里程"]) + Convert.ToDouble(row["miles"]);

                        //viewRow["计价"] = Convert.ToDouble(viewRow["计价"]) + Convert.ToDouble(row["miles"]) * mileprice;
                    }
                }
            }

            //工时统计表
            View_HoursDT = StatisticsAccess.GetViewHourDT(_view_StartDate, days);
            DataTable hoursRecordDT = StatisticsAccess.GetHoursRecordInDays(_view_StartDate.ToString("yyyy-MM-dd"), _view_EndDate.ToString("yyyy-MM-dd"));
            if (null != hoursRecordDT && hoursRecordDT.Rows.Count > 0)
            {
                View_HoursDT.PrimaryKey = new DataColumn[] { View_HoursDT.Columns["ID"] };
                foreach (DataRow row in hoursRecordDT.Rows)
                {
                    DataRow viewRow = View_HoursDT.Rows.Find(row["UserID"].ToString());
                    if (null != viewRow)
                    {
                        viewRow[row["date"].ToString().Substring(5)] = Convert.ToDouble(viewRow[row["date"].ToString().Substring(5)]) + Convert.ToDouble(row["hour"]);

                        viewRow["总工时"] = Convert.ToDouble(viewRow["总工时"]) + Convert.ToDouble(row["hour"]);

                        viewRow["计价"] = Convert.ToDouble(viewRow["计价"]) + Convert.ToDouble(row["hour"]) * hourPrice;
                    }
                }
            }

            if (View_SingleDriver != null)
            {
                View_SafeMilesDT.DefaultView.RowFilter = "ID = '" + View_SingleDriver.ID + "' ";
                View_FollowMilesDT.DefaultView.RowFilter = "ID = '" + View_SingleDriver.ID + "'";
                View_HoursDT.DefaultView.RowFilter = "ID = '" + View_SingleDriver.ID + "'";
            }
            else if (!string.IsNullOrEmpty(_view.TBSingleDriverName.Text))
            {
                string str = " 司机姓名 like '%"+_view.TBSingleDriverName.Text.Trim()+"%'";
                View_HoursDT.DefaultView.RowFilter = View_FollowMilesDT.DefaultView.RowFilter = View_SafeMilesDT.DefaultView.RowFilter = str;
            }

            _view.SetView_dgv_Visibility();
        }

        /// <summary>
        /// 以班组的ID返回班组的名称 0：早班；1：休班；2：白班；3：夜班
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        private string GetClassNameByID(string ID)
        {
            string _class = "";
            switch (ID)
            {
                case "0":
                    _class = "早班";
                    break;
                case "1":
                    _class = "休班";
                    break;
                case "2":
                    _class = "白班";
                    break;
                case "3":
                    _class = "夜班";
                    break;
                default:
                    _class = ID;
                    break;
            }
            return _class;
        }

        /// <summary>
        /// 返回热备，备用，调车，试车线特殊司机组的名称
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private string GetSpecialGroup(string type)
        {
            string group = null;
            switch(type)
            {
                case"1":
                    group = "热备";
                    break;
                case "2":
                    group = "调车";
                    break;
                case "3":
                    group = "试车线";
                    break;
                case "4":
                    group = "备班";
                    break;
            }
            return group;
        }


        public bool DeleAutoDgvRow(DataRow row)
        {
            try
            {
                AutoStaResultDT.Rows.Remove(row);
            }
            catch (System.Exception ex)
            {
                return false;
            }
            return true;
        }

        private void InitUnStatisticsDatesCollections()
        {
            DataTable UnAssignDT = StatisticsAccess.GetUnStatisticsDates();
            if (null == UnAssignDT || UnAssignDT.Rows.Count < 1)
                return ;

            _unStatisticsDatesCollections = new ObservableCollection<UnStatisticsDatesModel>();
            for (int i = 0; i < UnAssignDT.Rows.Count; i ++ )
            {
                UnStatisticsDatesModel model = new UnStatisticsDatesModel();
                model.ID = UnAssignDT.Rows[i]["ID"].ToString();
                model.AssignDate = UnAssignDT.Rows[i]["AssignDate"].ToString();
                model.TableName = UnAssignDT.Rows[i]["TableName"].ToString();

                _unStatisticsDatesCollections.Add(model);
            }
        }

        private void InitParameters()
        {
            DataTable paraDT = StatisticsAccess.GetParaMeters();
            if (null == paraDT || paraDT.Rows.Count < 1)
            {
                MessageBoxHelper.ShowError("获取公里数、工时统计参数时出现异常，请仔细检查公里数自动生成处结果是否正确！");
                return;
            }

            this._milePrice = paraDT.Rows[0]["MilePrice"].ToString();
            this._hourPrice = paraDT.Rows[0]["HourPrice"].ToString();

            //DicParaMeters.Add("InMiles", paraDT.Rows[0]["InMiles"].ToString());
            //DicParaMeters.Add("OutMiles", paraDT.Rows[0]["OutMiles"].ToString());
            //DicParaMeters.Add("UpToChangedMiles", paraDT.Rows[0]["UpToChangedMiles"].ToString());
            //DicParaMeters.Add("HKHUpToChangedMiles", paraDT.Rows[0]["HKHUpToChangedMiles"].ToString());
            //DicParaMeters.Add("DownToChangedMiles", paraDT.Rows[0]["DownToChangedMiles"].ToString());
            //DicParaMeters.Add("TotalMiles", paraDT.Rows[0]["TotalMiles"].ToString());
            //DicParaMeters.Add("HKHTotalMiles", paraDT.Rows[0]["HKHTotalMiles"].ToString());
            //DicParaMeters.Add("MilePrice", paraDT.Rows[0]["MilePrice"].ToString());
            //DicParaMeters.Add("HourPrice", paraDT.Rows[0]["HourPrice"].ToString());

            //UpdateParas();
        }

        ///// <summary>
        ///// 从字典中取出参数更新
        ///// </summary>
        //private void UpdateParas()
        //{
        //    DicParaMeters.TryGetValue("InMiles", out _inMiles);
        //    DicParaMeters.TryGetValue("OutMiles", out _outMiles);
        //    DicParaMeters.TryGetValue("UpToChangedMiles", out _upToChangedMiles);
        //    DicParaMeters.TryGetValue("HKHUpToChangedMiles", out _hkhupToChangedMiles);
        //    DicParaMeters.TryGetValue("DownToChangedMiles", out _downToChangedMiles);
        //    DicParaMeters.TryGetValue("TotalMiles", out _totalMiles);
        //    DicParaMeters.TryGetValue("HKHTotalMiles", out _hkhtotalMiles);
        //    DicParaMeters.TryGetValue("MilePrice", out _milePrice);
        //    DicParaMeters.TryGetValue("HourPrice", out _hourPrice);

        //    OnPropertyChanged("InMiles");
        //    OnPropertyChanged("OutMiles");
        //    OnPropertyChanged("UpToChangedMiles");
        //    OnPropertyChanged("HKHUpToChangedMiles");
        //    OnPropertyChanged("DownToChangedMiles");
        //    OnPropertyChanged("TotalMiles");
        //    OnPropertyChanged("HKHTotalMiles");
        //    OnPropertyChanged("MilePrice");
        //    OnPropertyChanged("HourPrice");
        //}

        /// <summary>
        /// 更新字典中的参数值
        /// </summary>
        //private void UpdateDicParaMeters()
        //{
        //    DicParaMeters["InMiles"] = _inMiles;
        //    DicParaMeters["OutMiles"] = _outMiles;
        //    DicParaMeters["UpToChangedMiles"] = _upToChangedMiles;
        //    DicParaMeters["HKHUpToChangedMiles"] = _hkhupToChangedMiles;
        //    DicParaMeters["DownToChangedMiles"] = _downToChangedMiles;
        //    DicParaMeters["TotalMiles"] = _totalMiles;
        //    DicParaMeters["HKHTotalMiles"] = _hkhupToChangedMiles;
        //    DicParaMeters["MilePrice"] = _milePrice;
        //    DicParaMeters["HourPrice"] = _hourPrice;
        //}

        private string Validate(string _value)
        {
            string error = null;
            if (string.IsNullOrEmpty(_value))
                error = "不可为空";
            if (!Regex.IsMatch(_value, @"^(\d+\.)?\d+$"))
            {
                error = "请输入正确的数字格式！";
            }
            if (_value.Length > 7)
            {
                error = "数值范围过大，请确认";
            }
            return error;    
        }

        //private void Para_EditCommand_Method()
        //{
        //    this.ReadOnly = false;
        //}

        //private bool Can_Para_EditCommand_Method()
        //{
        //    return _readOnly;
        //}

        //private void Para_Save_Method()
        //{
        //    if (_statisticsAccess.UpdateParaMeters(_inMiles,_outMiles,_upToChangedMiles,_hkhupToChangedMiles,_downToChangedMiles,_totalMiles,_hkhtotalMiles))
        //    { 
        //        MessageBoxHelper.ShowTips("统计参数修改保存成功！");
        //        UpdateDicParaMeters();

        //        ReadOnly = true;
        //    }
        //    else
        //    {
        //        MessageBoxHelper.ShowError("保存失败，请确认格式输入正确后重试！");
        //        UpdateParas();  //失败便返回原来的参数
        //    }
        //}

        //private bool Can_Para_Save_Method()
        //{
        //    return !_readOnly && string.IsNullOrEmpty(Validate(_inMiles))
        //        && string.IsNullOrEmpty(Validate(_outMiles))
        //        && string.IsNullOrEmpty(Validate(_upToChangedMiles))
        //        && string.IsNullOrEmpty(Validate(_hkhupToChangedMiles))
        //        && string.IsNullOrEmpty(Validate(_downToChangedMiles))
        //        && string.IsNullOrEmpty(Validate(_totalMiles))
        //        && string.IsNullOrEmpty(Validate(_hkhtotalMiles))
        //        && string.IsNullOrEmpty(Validate(_milePrice))
        //        && string.IsNullOrEmpty(Validate(_hourPrice));
        //}

        //private void Para_Cancel_Method()
        //{
        //    UpdateParas();
        //    ReadOnly = true;
        //}

        //private bool Can_Para_Cancel_Method()
        //{
        //    return !_readOnly;
        //}
    }
}
